// Some utility methods
// ====================

define(['jquery', 'underscore'], function($, _) {

  return {
    /**
     * Use JSON.parse to parse JSON string, catch any exception
     * and log to console.
     */
    parseJSON: function(string) {
      try {
        return JSON.parse(string)
      } catch (e) {
        console.error(e)
      }
    },

    /**
     * General process utility to parse Result from Server
     */
    processResult: function(response, success, failure) {
      var result = this.parseJSON(response)
      if (!!result && parseInt(result.code) === 0) {
        success && success(result)
      } else if (!!failure) {
        failure(result)
      } else {
        console.warn('No function found handling result: ', result)
      }
    },

    /**
     * Utility to request verify code
     */
    requestVerifyCode: function(mobile, success, failure) {
      $that = this
      $.showIndicator()
      $.post(__CTX__.root + '/sms/verify-code', { 'mobile': mobile })
        .done(function(response) {
          $.hideIndicator()
          $that.processResult(response, success, function() {
            $.toast('获取验证码失败')
            failure && failure()
          })
        })
    },

    /**
     * Utility to translate rem length to pixel length
     */
    rem2px: function(rem) {
      var fontSize =
        parseFloat(window.getComputedStyle(document.documentElement).fontSize)
      var value = parseFloat(rem) * fontSize
      if (typeof rem === 'string' && /rem$/.test(rem)) {
        return value + 'px'
      }
      return value
    }
  }
})